#!/usr/bin/env python

'''
A simple GTP controller stand-alone script.
'''

from socket import socket, AF_INET, SOCK_STREAM

BLACK_PORT = 50007
WHITE_PORT = 50008

BOARD_SIZE = 4


def get_connection(port):

    sockobj = socket(AF_INET, SOCK_STREAM)
    sockobj.bind(('', port))
    sockobj.listen(1)
    
    connection, address = sockobj.accept()
    print 'Controller connected by', address, 'at port', port
    
    return connection


def send_command(file, cmd):
    """ send the command and return the response. """
    file.write(cmd)
    file.flush()
    response = ' '
    
    while response.isspace():
        response = file.readline()
    
    return response
    

def do_play(black_file, white_file):
    
    board_cmd = 'boardsize %d\n' % BOARD_SIZE
    
    send_command(black_file, board_cmd)    
    print 'Black board size set'
    
    send_command(white_file, board_cmd)    
    print 'White board size set'
    
    #FIXME, vienen lineas vacias, hay que leer bien
    while True: #cuando termina??
        
        vertex = send_command(black_file, 'genmove black\n')[2:-1]
        print 'black plays ', vertex
        send_command(white_file, 'play black %s\n' % vertex)
        
        vertex = send_command(white_file, 'genmove white\n')[2:-1]
        print 'white plays ', vertex
        send_command(black_file, 'play white %s\n' % vertex)


def play():
    black_socket = get_connection(BLACK_PORT) 
    white_socket = get_connection(WHITE_PORT)
    
    black_file = black_socket.makefile()
    white_file = white_socket.makefile()
    
    try:
    
        do_play(black_file, white_file)
    
    finally:
    
        black_file.close()
        white_file.close()
        
        black_socket.close()
        white_socket.close()
    

if __name__ == "__main__":
    
    #subprocess.Popen(['./network_game.py', '-s', '-p', '%d' % BLACK_PORT])
    #subprocess.Popen(['./network_game.py', '-c', 'w', '-s', '-p', '%d' % WHITE_PORT])
    
    play()
    